const {CheckInfo}=require('../service/user.service')
const bcrypt=require('bcryptjs')
const {userFormatError,userAlreadyExited,userNotExist, userLoginError, userPasswordError }=require('../consitant/error')
const userValidator=async(ctx,next)=>{
    const {username,password,nickname}=ctx.request.body
    if(!username||!password||!nickname){
        console.error("用户名或者密码,nickname,为空",ctx.request.body)
        ctx.app.emit('error',userFormatError,ctx)
        
        return 
    }
    await next()
}
const verifyUser=async(ctx,next)=>{
    const {username}=ctx.request.body
    console.log(username)
    console.log(await CheckInfo({username}))
    if(await CheckInfo({username})){
      ctx.app.emit('error',userAlreadyExited,ctx)
        return
    }
    await next()
}
const bcryptPassword=async(ctx,next)=>{
    const {password}=ctx.request.body
    if(password==''){
        ctx.request.body.password=null
        await next()
    }
    const salt =bcrypt.genSaltSync(5)
     const hash =bcrypt.hashSync(password,salt)
     ctx.request.body.password=hash
     await next()
    
}
const verifyLogin =async (ctx,next)=>{
      //1是否存在
      //2是否匹配
      const {username,password}=ctx.request.body
 try{
    const res=await CheckInfo({username})
    if(!res){
        ctx.app.emit('error',userNotExist,ctx)
        return
    }
    if(!bcrypt.compareSync(password,res.password)){
        ctx.app.emit('error',userPasswordError,ctx)
        return
    }

 }catch(err){
    ctx.app.emit('error',userLoginError,ctx)
    return
 }
      await next()
}

module.exports={
    userValidator,
    verifyUser,
    bcryptPassword,
    verifyLogin
}